#include "./../../lvgl/lvgl.h"
#include "./../../lvgl/demos/lv_demos.h"
#include "./../../lv_drivers/display/fbdev.h"
#include "./../../lv_drivers/indev/evdev.h"
#include <unistd.h>
#include <pthread.h>
#include <time.h>
#include <sys/time.h>
#include <string.h>

#include "./../../inc/homePage.h"
#include "./../../inc/album.h"
#include "./../../inc/page_manager.h"
#include "./../../inc/setting.h"
#include "./../../inc/login.h"

lv_obj_t * tic_tac_toe_screen  = NULL;
static lv_obj_t * cells[3][3]  = {NULL};
static lv_obj_t * status_label = NULL;
static char board[3][3]        = {{' ', ' ', ' '}, {' ', ' ', ' '}, {' ', ' ', ' '}};
static char current_player     = 'X'; // 当前玩家
static int game_over           = CLOSE_MODE;

static void game_card_init(lv_obj_t * parent);
static void check_winner(void);
static void reset_game(void);
static void show_symbol_in_cell(lv_obj_t * cell, char symbol);
static void cell_clicked(lv_event_t * e);
static void exit_game(lv_event_t * e);
static void restart_game_event_cb(lv_event_t * e);

void tic_tac_toe_init(void)
{
    tic_tac_toe_screen = lv_obj_create(NULL);
    lv_obj_set_style_bg_color(tic_tac_toe_screen, lv_color_hex(BLACK), LV_PART_MAIN);
    lv_obj_set_style_bg_opa(tic_tac_toe_screen, LV_OPA_COVER, LV_PART_MAIN);
    lv_obj_set_style_pad_all(tic_tac_toe_screen, 0, LV_PART_MAIN);
    lv_obj_clear_flag(tic_tac_toe_screen, LV_OBJ_FLAG_SCROLLABLE); // 不可滚动

    lv_obj_t * game_bg = lv_img_create(tic_tac_toe_screen);
    lv_img_set_src(game_bg, "S:res/ui/game_bg.png");

    show_status_bar(tic_tac_toe_screen);
    show_taskbar(tic_tac_toe_screen);

    status_label = lv_label_create(tic_tac_toe_screen);
    lv_label_set_text(status_label, "当前玩家: X");
    lv_obj_set_style_text_color(status_label, lv_color_hex(WHITE), LV_PART_MAIN);
    LV_FONT_DECLARE(SourceHanSansCN_Bold_20);
    lv_obj_set_style_text_font(status_label, &SourceHanSansCN_Bold_20, LV_PART_MAIN | LV_STATE_DEFAULT);
    lv_obj_align(status_label, LV_ALIGN_TOP_MID, 0, 50);

    game_card_init(tic_tac_toe_screen);

    lv_obj_t * button_container = lv_obj_create(tic_tac_toe_screen);
    lv_obj_set_size(button_container, LV_PCT(25), 150);
    lv_obj_set_style_bg_opa(button_container, LV_OPA_0, LV_PART_MAIN);
    lv_obj_set_style_border_width(button_container, 0, LV_PART_MAIN);
    lv_obj_align(button_container, LV_ALIGN_RIGHT_MID, -20, 0);

    // 重新开始按钮
    lv_obj_t * restart_btn = lv_btn_create(tic_tac_toe_screen);
    lv_obj_set_size(restart_btn, 64, 64);
    lv_obj_set_style_radius(restart_btn, 30, LV_PART_MAIN);
    lv_obj_set_style_bg_opa(restart_btn, LV_OPA_0, LV_PART_MAIN); // 完全透明
    lv_obj_set_style_bg_color(restart_btn, lv_color_hex(0x27AE60), LV_STATE_PRESSED);
    lv_obj_align(restart_btn, LV_ALIGN_CENTER, 250, -20);

    lv_obj_t * restart_img = lv_img_create(restart_btn);
    lv_img_set_src(restart_img, "S:res/ui/restart_game.png");
    lv_obj_center(restart_img);
    lv_obj_add_event_cb(restart_btn, restart_game_event_cb, LV_EVENT_CLICKED, NULL);

    navigate_to(tic_tac_toe_screen);
}

// 棋盘和单元格创建
static void game_card_init(lv_obj_t * parent)
{
    lv_obj_t * game_card = lv_obj_create(parent);
    lv_obj_set_size(game_card, 320, 320);
    lv_obj_set_style_bg_color(game_card, lv_color_hex(0x333333), LV_PART_MAIN);
    lv_obj_set_style_radius(game_card, 0, LV_PART_MAIN);
    lv_obj_set_style_pad_all(game_card, 0, LV_PART_MAIN);
    lv_obj_clear_flag(game_card, LV_OBJ_FLAG_SCROLLABLE); // 不可滚动
    lv_obj_set_style_border_width(game_card, 0, LV_PART_MAIN);
    lv_obj_align(game_card, LV_ALIGN_CENTER, 0, 0);

    const int grid_size = 3;
    const int cell_size = 100;
    const int gap       = 5;

    for(int row = 0; row < grid_size; row++) {
        for(int col = 0; col < grid_size; col++) {
            lv_obj_t * cell = lv_btn_create(game_card);
            lv_obj_set_size(cell, cell_size, cell_size);
            lv_obj_set_pos(cell, col * (cell_size + gap) + gap, row * (cell_size + gap) + gap);

            lv_obj_set_style_radius(cell, 0, LV_PART_MAIN);
            lv_obj_set_style_pad_all(cell, 0, LV_PART_MAIN);
            lv_obj_set_style_bg_color(cell, lv_color_hex(WHITE), LV_PART_MAIN);
            (cell, 0, LV_PART_MAIN);
            lv_obj_set_style_border_color(cell, lv_color_hex(0x999999), LV_PART_MAIN);

            lv_obj_add_event_cb(cell, cell_clicked, LV_EVENT_CLICKED, NULL);
            cells[row][col] = cell;
        }
    }
}

// 单元格点击事件
static void cell_clicked(lv_event_t * e)
{
    // 游戏结束时，忽略点击
    if(game_over) return;

    lv_obj_t * target_cell = lv_event_get_target(e);

    int clicked_row = -1, clicked_col = -1;
    for(int row = 0; row < 3; row++) {
        for(int col = 0; col < 3; col++) {
            if(cells[row][col] == target_cell) {
                clicked_row = row;
                clicked_col = col;
                break;
            }
        }
        if(clicked_row != -1) break;
    }

    //  检查单元格是否为空（未被占用）
    if(board[clicked_row][clicked_col] == ' ') {
        board[clicked_row][clicked_col] = current_player;
        show_symbol_in_cell(target_cell, current_player);

        check_winner();
    }
}

// 检查游戏结果
static void check_winner(void)
{
    // 1. 检查行（3行，每行3个元素相同且非空）
    for(int row = 0; row < 3; row++) {
        if(board[row][0] != ' ' && board[row][0] == board[row][1] && board[row][1] == board[row][2]) {
            lv_label_set_text_fmt(status_label, "玩家 %c 获胜!", current_player);
            game_over = 1;
            return;
        }
    }

    // 2. 检查列（3列，每列3个元素相同且非空）
    for(int col = 0; col < 3; col++) {
        if(board[0][col] != ' ' && board[0][col] == board[1][col] && board[1][col] == board[2][col]) {
            lv_label_set_text_fmt(status_label, "玩家 %c 获胜!", current_player);
            game_over = 1;
            return;
        }
    }

    // 3. 检查对角线（2条对角线，元素相同且非空）
    if(board[0][0] != ' ' && board[0][0] == board[1][1] && board[1][1] == board[2][2]) {
        lv_label_set_text_fmt(status_label, "玩家 %c 获胜!", current_player);
        game_over = 1;
        return;
    }
    if(board[0][2] != ' ' && board[0][2] == board[1][1] && board[1][1] == board[2][0]) {
        lv_label_set_text_fmt(status_label, "玩家 %c 获胜!", current_player);
        game_over = 1;
        return;
    }

    // 4. 检查平局（所有单元格非空，且无胜者）
    int is_full = 1;
    for(int row = 0; row < 3; row++) {
        for(int col = 0; col < 3; col++) {
            if(board[row][col] == ' ') {
                is_full = 0;
                break;
            }
        }
        if(!is_full) break;
    }
    if(is_full) {
        lv_label_set_text(status_label, "平局!");
        game_over = 1;
        return;
    }

    // 5. 游戏继续切换玩家
    current_player = (current_player == 'X') ? 'O' : 'X';
    lv_label_set_text_fmt(status_label, "当前玩家: %c", current_player);
}

// 在单元格中显示X/O图片 -
static void show_symbol_in_cell(lv_obj_t * cell, char symbol)
{
    //  先删除单元格中已有的图片
    lv_obj_t * child = lv_obj_get_child(cell, 0);
    if(child) {
        lv_obj_del(child);
    }

    // 创建图片对象并设置资源
    lv_obj_t * img = lv_img_create(cell);
    if(symbol == 'X') {
        lv_img_set_src(img, "S:res/ui/x.png");
    } else if(symbol == 'O') {
        lv_img_set_src(img, "S:res/ui/o.png");
    }
    lv_obj_center(img);
}

//  重新开始游戏
void restart_game()
{
    //  清空棋盘数据
    memset(board, ' ', sizeof(board)); // 批量置空，更高效

    //  清除所有单元格中的图片
    for(int row = 0; row < 3; row++) {
        for(int col = 0; col < 3; col++) {
            lv_obj_t * child = lv_obj_get_child(cells[row][col], 0);
            if(child) {
                lv_obj_del(child);
            }
        }
    }

    // 重置游戏状态
    current_player = 'X';
    game_over      = 0;
    lv_label_set_text(status_label, "当前玩家: X");
}

static void restart_game_event_cb(lv_event_t * e)
{
    //  清空棋盘数据
    memset(board, ' ', sizeof(board)); // 批量置空，更高效

    //  清除所有单元格中的图片
    for(int row = 0; row < 3; row++) {
        for(int col = 0; col < 3; col++) {
            lv_obj_t * child = lv_obj_get_child(cells[row][col], 0);
            if(child) {
                lv_obj_del(child);
            }
        }
    }

    // 重置游戏状态
    current_player = 'X';
    game_over      = 0;
    lv_label_set_text(status_label, "当前玩家: X");
}

// 退出游戏
static void exit_game(lv_event_t * e)
{
    // // 导航到主页面（使用你项目中已有的"返回主页面"逻辑）
    // // 注：如果homePage的初始化函数是home_page_init()，请替换为实际函数名
    // home_page_init(); // 示例：假设主页面初始化函数为home_page_init()

    // // （可选）删除当前游戏页面，避免内存泄漏
    // if(tic_tac_toe_screen) {
    //     lv_obj_del(tic_tac_toe_screen);
    //     tic_tac_toe_screen = NULL;
    // }
}